<template>
    <VRow>
        <VCol cols="12" md="2">
            <v-treeview
            :items="galleryGroupTree"
            color="primary"
            item-value="id"
            item-title="label"
            expand-icon="tabler-chevron-right"
            collapse-icon="tabler-chevron-down"
            @click:select="selectNode"
        ></v-treeview>
        </VCol>
        <VCol cols="12" md="10">
            <VDataTableServer :loading="tableLoading" v-model:items-per-page="queryParams.pageSize" v-model:model-value="selectedRows" v-model:page="queryParams.pageNum" v-model="selected" :items="data" item-value="id" :items-length="total" :headers="headers">
            <template v-slot:headers="{ allSelected, someSelected, selectAll }">
            </template>
            <template v-slot:body="{ items }">
                <v-empty-state v-if="!items.length"
                    icon="tabler-search"
                    headline="暂无数据"
                    title="这里还没有任何记录"
                ></v-empty-state>
                <v-responsive
                    class="overflow-y-hidden overflow-x-hidden"

                >
                <VRow>
                <VCol v-for="item in items">
                  <v-hover>
                    <template v-slot:default="{ isHovering, props }">
                        <VCard
                        v-bind="props"
                        width="250"
                        height="250">
                            <v-overlay
                              :model-value="isHovering"
                              class="align-center justify-center"
                              contained
                            >
                            <section v-if="item.mall">
                              <v-btn v-if="item.galleryMallStatus == 1"
                                color="warning"
                                @click="unShelf(item)"
                                :loading = "loading"
                              >
                                下架
                              </v-btn>
                              <v-btn v-if="item.galleryMallStatus == 2"
                                color="success"
                                @click="shelf(item)"
                                :loading = "loading"  
                              >
                                上架
                              </v-btn>
                            </section>
                            <section v-else>
                              <v-btn
                                color="primary"
                                @click="publish(item)"
                              >
                                发布商品
                              </v-btn>
                            </section>
                            
                              
                            </v-overlay>
                            <v-lazy @update:modelValue="loadElementImg(item, 'stock')">
                            <VImg
                            aspect-ratio="1"
                            :src="item.src"
                            cover
                            />
                            </v-lazy>
                        </VCard>
                      </template>
                    </v-hover>
                </VCol>
                </VRow>
            </v-responsive>
            </template>
            <!-- pagination -->
            <template #bottom>
                <TablePagination v-model:page="queryParams.pageNum" v-model:items-per-page="queryParams.pageSize" :total-items="total" @update:page="getList" @update:items-per-page="getList" />
            </template>
            </VDataTableServer>
        </VCol>
    </VRow>
    <VDialog
    :width="$vuetify.display.smAndDown ? 'auto' : 900"
    :model-value="visible"
    @after-leave="handleFormReset"
  >
    <!-- Dialog close btn -->
    <DialogCloseBtn @click="visible = false" />

    <VCard class="pa-sm-10 pa-2">
      <VCardText>
        <!-- 👉 Title -->
        <h4 class="text-h4 text-center mb-2">
          发布素材商品
        </h4>
        <!-- 👉 Form -->
        <VForm
          class="mt-6"
          ref="formRef"
          @submit.prevent="handleSubmit"
        >
          <VRow>
            <VCol
              cols="12"
              md="6"
            >
              <AppTextField
                v-model="form.title"
                 :rules="formRules.title"
                label="标题"
                placeholder="标题"
              />
            </VCol>

            <VCol
              cols="12"
              md="6"
            >
            <AppTextField
                v-model="form.price"
                 :rules="formRules.price"
                type="number"
                hide-spin-buttons
                label="价格"
                placeholder="价格"
              />
            </VCol>

            <VCol
              cols="12"
            >
              <span class="mb-1">描述</span>
              <ProductDescriptionEditor
              v-model="form.description"
              placeholder="XXXXXXXXXX"
              class="border rounded"
              />
            </VCol>

            <!-- 👉 Submit and Cancel -->
            <VCol
              cols="12"
              class="d-flex flex-wrap justify-center gap-4"
            >
              <VBtn type="submit" :loading="loading">
                {{$t("tableOperate.confirm")}}
              </VBtn>

              <VBtn
                color="secondary"
                variant="tonal"
                @click="visible = false"
              >
                {{$t("tableOperate.cancel")}}
              </VBtn>
            </VCol>
          </VRow>
        </VForm>
      </VCardText>
    </VCard>
  </VDialog>
</template>

<script setup>
import * as Utils from "@/utils/index";
import { listGallery,publishToMall } from '@/api/mes/gallery';
import {galleryShelf,galleryUnshelf} from '@/api/gallery'
const { t } = useI18n()

const { proxy } = getCurrentInstance();

const loading = ref(false);
const visible = ref(false);

const queryFormRef = ref()

const queryParams = ref({
  pageNum: 1,
  pageSize: 20,
  isAsc: 'desc',
  orderByColumn: 'createTime',
  groupId:undefined
});


const formRef = ref()

const form = ref({
  galleryId: undefined,
  title: undefined,
  price: undefined,
  description: undefined,
});

const formRules = {
  galleryId:[
    v=>!!v || '元素图ID不能为空'
  ],
  title:[
    v=>!!v || '标题不能为空'
  ],
  price:[
    v=>v!=undefined || '价格不能为空'
  ]
}

const publish = (item) =>{
  form.value.galleryId = item.id
  visible.value = true
}

const shelf = async (item) =>{
  const _ids = item?.galleryMallId ? [item?.galleryMallId] : selected.value;
  if (_ids.length === 0) {
    proxy.$toast.warning("请先选择素材");
    return;
  }
  loading.value = true
  await galleryShelf({mallIds:_ids}).finally(()=>loading.value = false)
  proxy.$toast.success("上架成功");
  item.galleryMallStatus = 1
}

const unShelf = async (item) =>{
  const _ids = item?.galleryMallId ? [item?.galleryMallId] : selected.value;
  if (_ids.length === 0) {
    proxy.$toast.warning("请先选择素材");
    return;
  }
  loading.value = true
  await galleryUnshelf({mallIds:_ids}).finally(()=>loading.value = false)
  proxy.$toast.success("下架成功");
  item.galleryMallStatus = 2
}

const handleSubmit = async () => {
  const { valid } = await formRef.value.validate()
  if (!valid) {
    return
  }
  if (!form.value.description) {
    proxy.$toast.error("商品描述不能为空");
    return
  }
  loading.value = true
  console.log(publishToMall)
  await publishToMall(form.value).finally(()=>loading.value = false)
  proxy.$toast.success(t("common.toast.success"));
  visible.value = false;
  await getList();
}

const handleFormReset = () => {
  formRef.value.reset()
}

async function loadElementImg(item, type) {
  Utils.loadElementImg(item, type)
}

const handleReset = () => {
  // dateTimePicker.value.onClear()
  handleSearch()
}


const handleSearch = () => {
  queryParams.value.pageNum = 1;
  getList();
}



// Data table options
const total = ref(0);
const data = ref([]);
const tableLoading = ref(false);
// Headers
const headers = [
  {
    title: "素材商品",
    key: "galleryInfo",
    sortable: false,
  }
];

const selected = ref()

const galleryGroupTree = ref([])

Utils.getGalleryGroupTree().then(res=>{
  galleryGroupTree.value = res.data
})

const selectNode = ({id, value, path})=>{
  console.log(selected,id)
  if (queryParams.value.groupId == id) {
    handleReset()
    queryParams.value.groupId = undefined
    data.value = []
    return
  }
  queryParams.value.groupId = id
  getList()
}

function getList() {
  tableLoading.value = true;
  listGallery(queryParams.value).then((res) => {
    data.value = res.rows;
    total.value = res.total;
    tableLoading.value = false;
  });
}
getList();

</script>